#include "stdafx.h"

#include "video/video.h"

#include "util/check_glerror.h"

namespace natrium {
	namespace video {
		Video::Video():
			core::System("Video", core::Task::SINGLETHREADED_REPEATING),
			mWindow(new Window("MainWindow"))
		{
			addSetting("Width", &mWindow->mWidth);
			addSetting("Height", &mWindow->mHeight);
		
			addSetting("Fullscreen", &mWindow->mFullscreen);
			addSetting("AutoSizeWindow", &mWindow->mAutoSizeWindow);
			addSetting("Title", &mWindow->mTitle);
		}

		Video::~Video() {
		
		}

		bool Video::init() {
			bool result = System::init();

			gLog << "Creating Window: " 
				<< mWindow->mWidth << "x" << mWindow->mHeight << ", " 
				<< mWindow->mFullscreen << " " << mWindow->mAutoSizeWindow << " " << mWindow->getName();

			mWindow->create();

			//fetch OpenGL versions
			const GLubyte* renderer = glGetString(GL_RENDERER);
			const GLubyte* vendor = glGetString(GL_VENDOR);
			const GLubyte* version = glGetString(GL_VERSION);
			const GLubyte* glslVersion = glGetString(GL_SHADING_LANGUAGE_VERSION);
			GLint major;
			GLint minor;
			glGetIntegerv(GL_MAJOR_VERSION, &major);
			glGetIntegerv(GL_MINOR_VERSION, &minor);
			gLog << "OpenGL " << major << "." << minor << " [" << renderer << "], by " << vendor;
			gLog << "Version " << version << ", GLSL " << glslVersion;

			glewExperimental = GL_TRUE; //Goddamn...
		
			GLenum err = glewInit();
			if (err != GLEW_OK) {
				gLog.error() << "Failed to initialize GLEW! " << glewGetErrorString(err);
				return false;
			}
			glGetError(); //the GLEW initialization yields an error... catch it here and ignore it (which should be safe)

			glClearColor(0.2f, 0.2f, 0.2f, 1.0f);

			mChan.broadcast(WindowCreated(mWindow));
			return result;
		}

		void Video::update() {
			glfwSwapBuffers();
		}

		void Video::shutdown() {
			mWindow->destroy();
		}

		WindowCreated::WindowCreated(const std::shared_ptr<Window>& win): 
			mWindow(win) 
		{
		}
	}
}